'use strict';

const uidObj = require('uni-id');
// const uidPay = require('uni-pay');
const {
	XMLParser
} = require("fast-xml-parser");

const db = uniCloud.database();
const {
	mainSpaceId
} = require('config-main-space')
exports.main = async (event, context) => {
	let response = {
		mpserverscssComposedResponse: true,
		statusCode: 200,
		headers: {
			'content-type': 'text/xml;charset=utf-8'
		},
		body: `<xml><return_code><![CDATA[FAILD]]></return_code><return_msg><![CDATA[异常回调]]></return_msg></xml>`
	};
	let data = event.body
	if (event.isBase64Encoded) {
		data = new Buffer(data, 'base64').toString();
	}
	const path = event.path;
	// 错误记录
	const errorObj = {
		msg: ''
	};

	let res = {};
	let notifyType = 'payment';
	let payObj = {
		name: '微信支付',
		way: 'wxpay'
	};
	switch (path) {
		case '/':
		case '/syb-app':
			res = JSON.parse(data)
			payObj.name = '微信支付'
			payObj.way = 'sybApp'
			break;
		case '/wxpay':
		case '/wxpay-app':
		case '/wxpay-h5wx':
			const parser = new XMLParser();
			res = parser.parse(data);
			res = res.xml
			try {
				//特殊处理transaction_id
				let transaction_ids = data.split('<transaction_id><![CDATA[')
				if (transaction_ids.length > 0) {
					let transaction_id = transaction_ids[1].split("]]></transaction_id>")[0]
					res.transaction_id = transaction_id
				}
			} catch (e) {

			}

			break;
		case '/alipay':
		case '/alipay-app':
			var queryArr = data.split("&");
			queryArr.forEach(function(item) {
				var key = item.split("=")[0];
				var value = item.split("=")[1];
				res[key] = value;
			});
			res.total_fee = res.total_amount * 100
			res.transaction_id = res.trade_no
			payObj.name = '支付宝支付';
			payObj.way = 'alipay';
			break;
		default:
			break;
	}
	if (res && (res.return_code == 'SUCCESS' || res.result_code == 'SUCCESS' || res.trade_status ==
			'TRADE_SUCCESS') && notifyType == 'payment') {
		let outTradeNo = res.out_trade_no
		let totalFee = res.total_fee
		let transactionId = res.transaction_id
		let openid = res.openid
		// 系统订单号
		const [order_id] = outTradeNo.split('_');

		let orderRes = await db.collection('wmzmall-order')
			.where({
				is_delete: 0,
				order_id: order_id
			})
			.limit(1)
			.get();

		const [order] = orderRes.data;
		if (!(order && order._id)) {
			errorObj.msg = `订单[${outTradeNo}]不存在`;
		}
		let order_pay_money = order.order_pay_money || 0
		if (order.state != '待付款') {
			response.body = '已付款'
			return response;
		}
		/* else if (order.order_actural_paid != totalFee) {
			errorObj.msg = `订单[${outTradeNo}]支付金额不一致，[${order.order_actural_paid}] != [${totalFee}]`;
		} */

		if (errorObj.msg) {
			uniCloud.logger.info(errorObj.msg);
			// 记录error日志

			return response;
		}

		// 订单详情
		const orderDetailRes = await db.collection('wmzmall-order-detail').where({
			order_id: order.order_id
		}).get();
		if (!(orderDetailRes.data && orderDetailRes.data.length)) {
			errorObj.msg = `订单[${outTradeNo}]的商品不存在`;
		}

		if (errorObj.msg) {
			uniCloud.logger.info(errorObj.msg);
			// 记录error日志

			return response;
		}

		// 已省金额
		let member_economize = 0;
		orderDetailRes.data.forEach(x => {
			// 会员已省金额
			member_economize += x.economize_amount;
		});

		const uid = order.create_uid;
		const uname = order.order_member_name;
		// 当前时间
		const nowdate = Date.now();

		// 订单配置
		const orderConfig = await getOrderConfig(order.shop_id);

		const ip = event.headers['x-real-ip'];

		// 开启事务
		const dbtran = await db.startTransaction();
		try {

			const orderUpdateObj = {
				state: '已完成'
			}
			let order_pay_state = '已付款'
			order_pay_money = order_pay_money + totalFee
			orderUpdateObj.state = '待发货'
			if (order_pay_money < order.order_actural_paid) {
				order_pay_state = '待付款'
				orderUpdateObj.state = '待付款'
			}
			if (order.order_type === '调货订单') {
				orderUpdateObj.state = '待发货'
			}



			// 支付后扣减库存
			if (orderConfig.stock_ded_type == 2) {
				// 扣减库存
				orderUpdateObj.order_ded_stock = 1;
			}
			// 更改订单状态
			await dbtran.collection('wmzmall-order').doc(order._id).update({
				last_modify_time: nowdate,
				last_modify_uid: payObj.way,
				last_modify_uname: payObj.name,

				// 交易单号
				out_trade_no: outTradeNo,

				version: db.command.inc(1),
				order_pay_state: order_pay_state,
				order_pay_no: transactionId,
				order_pay_way: payObj.name,
				// 支付时间
				order_pay_time: nowdate,
				order_pay_money: order_pay_money,
				...orderUpdateObj
			});

			// 订单日志
			await dbtran.collection('wmzmall-order-log').add({
				order_id: order.order_id,
				log_type: '订单支付',
				current_state: orderUpdateObj.state,
				prev_state: '待付款',
				ip: ip,
				is_delete: 0,
				create_uid: uid,
				create_uname: uname,
				create_time: nowdate
			});


			// 提交事务
			await dbtran.commit();

			// 修改订单支付数据
			await db.collection('wmzmall-order-pay').where({
				order_id: order.order_id
			}).update({
				version: db.command.inc(1),
				pay_state: '已付款',
				pay_notify: event,
				pay_money: totalFee,
				pay_time: nowdate,
				pay_no: transactionId,
				pay_openid: openid
			});
			// 支付后扣减库存
			const memberRes = await db.collection('wmzmall-member').doc(uid).get();
			let [memberData = {}] = memberRes.data;
			let invitation_code = memberData.invitation_code
			let invitation_member_id = memberData.invitation_member_id
			for (let i = 0; i < orderDetailRes.data.length; i++) {
				let x = orderDetailRes.data[i];

				// 扣减SKU库存
				if (x.goods_sku) {
					if (!invitation_code || invitation_code === '8888') {
						await db.collection('wmzmall-goods-sku')
							.where({
								goods_id: x.goods_id,
								goods_sku: x.goods_sku,
								stock_num: db.command.gte(x.goods_num)
							})
							.update({
								stock_num: db.command.inc(-x.goods_num),
								sale_cnt: db.command.inc(x.goods_num)
							});
					} else {
						await db.collection('wmzmall-channel-goods-sku')
							.where({
								goods_id: x.goods_id,
								goods_sku: x.goods_sku,
								create_uid: invitation_member_id
							})
							.update({
								stock_num: db.command.inc(-x.goods_num),
								sale_cnt: db.command.inc(x.goods_num)
							});
					}
				}
			}

			let title = '收款';
			let cate = order.order_type;
			let type = 0;
			let appId = order.app_id;
			let shopId = order.shop_id;
			let orderNo = transactionId;
			let way = payObj.name;
			let payMoney = order.order_total_money;
			if (way.indexOf('支付宝') > -1) {
				way = '支付宝支付';
			}
			let conbo_buy = 0
			if (order.order_type === '调货订单') {
				await db.collection('wmzmall-goods-exchange').doc(order.order_id).update({
					status: 2
				})
			} else if (order.order_type === '套餐') {
				conbo_buy = 1
			} else {
				//增加云仓
				/* let cloud_th_total = 0
				for (let i = 0; i < orderDetailRes.data.length; i++) {
					let x = orderDetailRes.data[i];
					//增加渠道商品表库存
					let channelGoodsSku = await db.collection('wmzmall-channel-goods-sku')
						.where({
							goods_id: x.goods_id,
							goods_sku: x.goods_sku,
							create_uid: uid
						}).get()
					if (channelGoodsSku.data.length > 0) {
						await db.collection('wmzmall-channel-goods-sku').doc(channelGoodsSku.data[0]._id)
							.update({
								stock_num: db.command.inc(x.goods_num),
								sale_cnt: db.command.inc(x.goods_num)
							})
					} else {
						let goodsSkuRes = await db.collection('wmzmall-goods-sku')
							.where({
								goods_id: x.goods_id,
								goods_sku: x.goods_sku
							}).get()
						goodsSkuRes = goodsSkuRes.data[0]
						goodsSkuRes.create_uid = uid
						goodsSkuRes.create_uname = uname
						goodsSkuRes.stock_num = x.goods_num
						goodsSkuRes.sale_cnt = x.goods_num
						delete goodsSkuRes._id
						await db.collection('wmzmall-channel-goods-sku').add(goodsSkuRes)
					}
					//增加云仓库存
					cloud_th_total += x.goods_num * 1
					console.log(cloud_th_total)
					let cloudStockRes = await db.collection('wmzmall-cloud-stock')
						.where({
							goods_id: x.goods_id,
							goods_sku_id: x.goods_sku_id,
							create_uid: uid
						}).get()
					cloudStockRes = cloudStockRes.data
					if (cloudStockRes.length > 0) {
						await db.collection('wmzmall-cloud-stock').doc(cloudStockRes[0]._id).update({
							goods_num: db.command.inc(x.goods_num)
						})
					} else {
						await db.collection('wmzmall-cloud-stock').add({
							goods_id: x.goods_id,
							goods_name: x.goods_name,
							goods_img: x.goods_img,
							goods_num: x.goods_num,
							goods_price: x.goods_price,
							goods_sku: x.goods_sku,
							goods_sku_name: x.goods_sku_name,
							goods_sku_img: x.goods_sku_img,
							goods_sku_id: x.goods_sku_id,
							is_delete: 0,
							create_uid: uid,
							create_uname: uname,
							app_id: appId,
							shop_id: shopId,
							create_time: nowdate
						})
					}
					//增加提货记录
					await db.collection('wmzmall-cloud-stock-logs').add({
						goods_id: x.goods_id,
						goods_name: x.goods_name,
						goods_img: x.goods_img,
						goods_num: x.goods_num,
						goods_price: x.goods_price,
						goods_sku: x.goods_sku,
						goods_sku_name: x.goods_sku_name,
						goods_sku_img: x.goods_sku_img,
						goods_sku_id: x.goods_sku_id,
						is_delete: 0,
						create_uid: uid,
						create_uname: uname,
						create_time: nowdate,
						app_id: appId,
						shop_id: shopId,
						type: 0 //进货
					})
				} */

				// 修改下单人 累计消费、已省金额
				await db.collection('wmzmall-member').doc(uid).update({
					member_monetary: db.command.inc(totalFee),
					member_economize: db.command.inc(member_economize),
					cloud_th_total: db.command.inc(cloud_th_total),
					conbo_buy: conbo_buy
				});
			}


			let shopie = {
				app_id: appId,
				shop_id: shopId,
				order_no: orderNo,
				title: title,
				cate: cate,
				type: type,
				way: way,
				money: payMoney,
				creator_id: order.creator_id,
				creator_name: order.creator_name,
				create_time: new Date().getTime(),
				is_delete: 0
			};
			let addShopieResult = await db.collection('wmzmall-shopie').add(shopie);
			let tdb = uniCloud.database({
				provider: 'tencent',
				spaceId: mainSpaceId
			})
			await tdb.collection('wmzmall-shopie').add(shopie)
			if (payObj.way == 'wxpay') {
				response.body =
					`<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
			} else if (payObj.way = 'alipay') {
				response.headers['content-type'] = 'text/plain';
				response.body = 'success';
			} else if (payObj.way = 'sybApp') {
				return 'success';
			}
		} catch (e) {
			// 回滚事务
			await dbtran.rollback();
			errorObj.msg = e.message;
		}

		if (errorObj.msg) {
			// 记录异常支付回调数据
			console.log(errorObj.msg)
		}
	}

	if (notifyType == 'refund') {
		if (payObj.way = 'alipay') {
			response.headers['content-type'] = 'text/plain';
			response.body = 'success';
		}
	}

	return response;
};

/**
 * 订单配置
 */
async function getOrderConfig(shop_id) {
	const configRes = await db.collection('wmzmall-order-parameter').where({
		shop_id: shop_id
	}).get();

	const [orderConfig = {}] = configRes.data;

	return orderConfig;
}

/**
 * 根据拼团活动ID获取数据
 * verify 验证活动是否有效
 */
async function getGroup(id, verify = true) {
	const groupRes = await db.collection('wmzmall-market-groupbuy').doc(id).field({
		goods_id: true,
		goods_obj: true,
		goods_price: true,
		group_num: true,
		group_members: true,
		group_begin_time: true,
		group_end_time: true,
		group_time: true,
		state: true,
		is_delete: true
	}).get();

	const [group] = groupRes.data;
	if (!(group && group._id)) throw new Error(`拼团活动不存在`);

	// 验证活动是否有效
	if (verify) {
		const nowdate = Date.now();
		if (!(group.is_delete == 0 && group.state == '启用')) throw new Error(`拼团活动已停止`);
		if (!(group.group_begin_time <= nowdate && group.group_end_time >= nowdate)) throw new Error(`拼团活动已结束`);

		// 活动到期时间
		group.expires_time = (group.group_end_time - nowdate) / 1000;
	}

	return group;
}

/**
 * 根据拼团活动团长ID获取数据
 * verify 验证是否过期
 */
async function getGroupChief(id, verify = true) {
	const groupRes = await db.collection('wmzmall-market-groupbuy-member').doc(id).get();

	const [group] = groupRes.data;
	if (!(group && group._id)) throw new Error(`当前拼单不存在`);

	if (group.is_delete == 1) throw new Error(`当前拼单已停止`);
	if (verify) {
		if (group.state == '已取消') throw new Error(`当前拼单活动已取消`);
		if (group.expire_time && Date.now() > group.expire_time) throw new Error(`拼单活动已结束`);
	}

	return group;
}

/**
 * 根据拼团活动订单ID获取数据
 * verify 验证是否过期
 */
async function getGroupChiefByOrder(id, verify = true) {
	const groupRes = await db.collection('wmzmall-market-groupbuy-member').where({
		order_id: id
	}).limit(1).get();

	const [group] = groupRes.data;
	if (!(group && group._id)) throw new Error(`您的开团不存在`);

	if (group.is_delete == 1) throw new Error(`您的开团已停止`);
	if (verify) {
		if (group.state == '已取消') throw new Error(`您的开团已取消`);
		if (group.expire_time && Date.now() > group.expire_time) throw new Error(`拼单活动已结束`);
	}

	return group;
}



/**
 * 将 UTC+0 转换为 UTC+8
 */
function toDateUTC8(date) {
	// 小时 UTC+0 转换为 UTC+8
	date.setHours(date.getHours() + 8);
	return date;
}